<?php
defined("_VALID_ACCESS") || die('Direct access forbidden');
class SCTV_MaintenanceAcceptance extends Module { 
	public function body(){
  		$this->rb = $this->init_module('Utils/RecordBrowser','SCTV_MaintenanceAcceptance','SCTV_MaintenanceAcceptance');	
    	$this->display_module($this->rb);
	}

    public function acceptance_change_request()
    {
		$manager =  CRM_ContactsCommon::get_my_record();
        $rb = $this->init_module('Utils/RecordBrowser','SCTV_MaintenanceAcceptanceChangeRequest');
        $rb->disable_actions();
        $rb->disable_pdf();
        $rb->disable_export();
        $rb->disable_filters();
        $rb->disable_search();
        $rb->disable_jump_to_record();
        $rpm = array(array('employee'=>$manager['id'], 'status'=>0), array('employee'=>false), array());
        $this->display_module($rb,$rpm,'show_data');
    }
	public function acceptance_report()
	{
		$tb = $this->init_module('Utils/TabbedBrowser');		
		$tb->set_tab('Báo cáo vật tư bảo trì', array($this, 'deployment_material_report'));				
		$tb->set_tab(__('Subnet Material Report'), array($this, 'subnet_material_report'));
        $tb->set_tab('Tổng hợp nhập xuất tồn', array($this, 'tong_hop_nhap_xuat_ton'));
        $tb->set_tab('Bảng kê nộp tiền bảo trì', array($this, 'bang_ke_nop_tien'));
        $tb->set_tab('Biên bản quyết toán vật tư bảo trì', array($this, 'bien_ban_quyet_toan'));
		$this->display_module($tb);	
		$tb->tag();
	}
    private function tham_so_bao_cao($report_name, $report_key){
        $form = $this->init_module('Libs/QuickForm',null,$report_name);
        $form->addElement('datepicker', $report_key . '_start_date', __('Start Date'));
        $form->addElement('datepicker', $report_key . '_end_date', __('End Date'));
        $form->addElement('autoselect', $report_key . '_truong_khu_vuc', 'Nhân viên quyết toán', array(), array(array('CRM_ContactsCommon','autoselect_contact_suggestbox'), array($crists, array('CRM_ContactsCommon', 'contact_format_default'))), array('CRM_ContactsCommon', 'contact_format_default'), array('style'=>'width:300px'));
		
		$optiongroup = SCTV_MaintenanceGroupCommon::get_maintenance_group();
		$form->addElement('select', $report_key . '_group', __('Maintenance Group'), $optiongroup);

        $form->addElement('submit',$report_key . '_submit_button',__('Show'));

        $defaults = array();
        $manager =  CRM_ContactsCommon::get_my_record();
        $is_area_manager = array_key_exists('area manager', $manager['access']);
        if($is_area_manager)
            $defaults[$report_key . '_truong_khu_vuc'] = $manager;
        $form->setDefaults($defaults);

        $form->display_as_row();

        if(isset($_REQUEST['submited']))
        {
            if(isset($_REQUEST[$report_key . '_start_date'])) $this->set_module_variable($report_key . '_start_date', $_REQUEST[$report_key . '_start_date']);
            if(isset($_REQUEST[$report_key . '_end_date'])) $this->set_module_variable($report_key . '_end_date', $_REQUEST[$report_key . '_end_date']);
            if(isset($_REQUEST[$report_key . '_truong_khu_vuc'])) $this->set_module_variable($report_key . '_truong_khu_vuc', $_REQUEST[$report_key . '_truong_khu_vuc']);
			if(isset($_REQUEST[$report_key . '_group'])) $this->set_module_variable($report_key . '_group', $_REQUEST[$report_key . '_group']);
        }
    }
    public function tong_hop_nhap_xuat_ton(){
        $this->tham_so_bao_cao('Tổng hợp nhật xuất tồn', 'tong_hop_nhap_xuat_ton');

        if($this->isset_module_variable('tong_hop_nhap_xuat_ton_start_date'))
        {
            $start_date = $this->get_module_variable('tong_hop_nhap_xuat_ton_start_date');
            $start_date = date('Y-m-d', strtotime($start_date));
            $end_date = $this->get_module_variable('tong_hop_nhap_xuat_ton_end_date');
            $end_date = date('Y-m-d', strtotime($end_date));
            $employee = $this->get_module_variable('tong_hop_nhap_xuat_ton_truong_khu_vuc');
			$group = $this->get_module_variable('tong_hop_nhap_xuat_ton_group');
			if($group == null){
				$group_is_null = true;
				$group = 0;
			}
			else{
				$group_is_null = false;
			}
			
            if(!empty($employee)){
                $records = DB::GetAll('select * from sctv_tong_hop_nhap_xuat_ton_bao_tri(%D, %D, %d, %b, %d)', array($start_date, $end_date, $employee, $group_is_null, $group));

                $gb = $this->init_module('Utils/GenericBrowser',null,'Tong hop nhap xuat ton');
                $columns = array(
                    array('name'=>__('STT'), 'width'=>'8'),
                    array('name'=>__('Mã vật tư'), 'width'=>'15'),
                    array('name'=>__('Tên vật tư'), 'width'=>'25'),
                    array('name'=>__('ĐVT'), 'width'=>'10'),
                    array('name'=>__('Tổng nhập trong kỳ'), 'width'=>'15'),
                    array('name'=>__('Tổng quyết toán trong kỳ'), 'width'=>'15'),
                    array('name'=>__('Tồn cuối kỳ'), 'width'=>'15')
                );
                $gb->set_table_columns($columns);
                $stt = 0;
                foreach($records as $key=>$record){
                    $stt++;
                    $input_amount = $record['input_amount'];
                    $output_amount = $record['output_amount'];
					$output_amount = $record['output_amount'];
                    $gb_row = $gb->get_new_row();
                    $gb_row->add_data($stt, $record['material_code'], $record['material_name'], $record['material_unit'], $input_amount, $output_amount, $input_amount - $output_amount);
                }

                $this->display_module($gb, array(false),'automatic_display');

                $keymd5 = md5(time());
                $_SESSION[$keymd5] = array(
                    'path'=>$this->get_path()
                );
                $print_href = 'href="modules/SCTV/MaintenanceAcceptance/exel_tong_hop_nhap_xuat_ton.php?'.http_build_query(array('key'=>$keymd5, 'cid'=>CID)).'" target="_blank"';
                Base_ActionBarCommon::add('excel', __('Excel'), $print_href);

                $print_href = 'href="modules/SCTV/MaintenanceAcceptance/print_tong_hop_nhap_xuat_ton.php?'.http_build_query(array('key'=>$keymd5, 'cid'=>CID)).'" target="_blank"';
                Base_ActionBarCommon::add('print', __('Print'), $print_href);
            }
        }
    }
    public function bang_ke_nop_tien() {
        $this->tham_so_bao_cao('Bảng kê nộp tiền bảo trì', 'bang_ke_nop_tien_lap_dat');

        if($this->isset_module_variable('bang_ke_nop_tien_lap_dat_start_date'))
        {
            $start_date = $this->get_module_variable('bang_ke_nop_tien_lap_dat_start_date');
            $start_date = date('Y-m-d', strtotime($start_date));
            $end_date = $this->get_module_variable('bang_ke_nop_tien_lap_dat_end_date');
            $end_date = date('Y-m-d', strtotime($end_date));
            $employee = $this->get_module_variable('bang_ke_nop_tien_lap_dat_truong_khu_vuc');
			$group = $this->get_module_variable('bang_ke_nop_tien_lap_dat_group');
			if($group == null){
				$group_is_null = true;
				$group = 0;
			}
			else{
				$group_is_null = false;
			}

            if(!empty($employee)){
                $records = DB::GetAll('select * from sctv_bang_ke_nop_tien_bao_tri(%D, %D, %d, %b, %d)', array($start_date, $end_date, $employee, $group_is_null, $group));

                $gb = $this->init_module('Utils/GenericBrowser',null,'bang ke nop tien lap dat');
                $columns = array(
                    array('name'=>__('STT'), 'width'=>'5'),
                    array('name'=>__('Nhân viên bảo trì '), 'width'=>'12'),
                    array('name'=>__('Số phiếu thu'), 'width'=>'7'),
                    //array('name'=>__('Số hợp đồng THC'), 'width'=>'7'),
                    //array('name'=>__('Số hợp đồng Internet'), 'width'=>'7'),
                    array('name'=>__('Ngày bảo trì '), 'width'=>'8'),
                    array('name'=>__('Tên khách hàng'), 'width'=>'15'),
                    //array('name'=>__('Phí hòa mạng'), 'width'=>'8'),
                    //array('name'=>__('Bán đầu số'), 'width'=>'8'),
                    array('name'=>__('Bán vật tư'), 'width'=>'12'),
                    array('name'=>__('Ký quỹ'), 'width'=>'12'),
                    array('name'=>__('Tổng cộng'), 'width'=>'15'),
                );
                $gb->set_table_columns($columns);
                $stt = 0;
                //$nv_phi_hoa_mang = 0;
                //$nv_tien_dau_so = 0;
                $nv_tien_vat_tu = 0;
                $nv_ky_quy = 0;
                $nv_tong_cong = 0;
                //$tong_phi_hoa_mang = 0;
                //$tong_tien_dau_so = 0;
                $tong_tien_vat_tu = 0;
                $tong_ky_quy = 0;
                $tong_tong_cong = 0;
                $prev_name = null;
                foreach($records as $key=>$record){
                    $stt++;
                    $employee_name = $record['employee_name'];
                    //$phi_hoa_mang = $record['phi_hoa_mang'];
                    //$tien_dau_so = $record['tien_dau_so'];
                    $tien_vat_tu = $record['tien_vat_tu'];
                    $ky_quy = $record['ky_quy'];
                    $tong_cong = $record['tong_cong'];

                    //$tong_phi_hoa_mang += $phi_hoa_mang;
                    //$tong_tien_dau_so += $tien_dau_so;
                    $tong_tien_vat_tu += $tien_vat_tu;
                    $tong_ky_quy += $ky_quy;
                    $tong_tong_cong += $tong_cong;

                    if($prev_name == null || $prev_name <> $employee_name){
                        if($prev_name != null){
                            $gb_row = $gb->get_new_row();
                            $gb_row->add_data(
                                null,
                                //null,
                                //null,
                                null,
                                null,
                                null,
                                '<strong>TỔNG</strong>',
                                //'<strong>'.number_format($nv_phi_hoa_mang, 0, ',', '.').'<strong>',
                                //'<strong>'.number_format($nv_tien_dau_so, 0, ',', '.').'<strong>',
                                '<strong>'.number_format($nv_tien_vat_tu, 0, ',', '.').'<strong>',
                                '<strong>'.number_format($nv_ky_quy, 0, ',', '.').'<strong>',
                                '<strong>'.number_format($nv_tong_cong, 0, ',', '.').'<strong>'
                            );
                        }
                        $stt = 1;
                        $prev_name = $employee_name;
                        //$nv_phi_hoa_mang = $phi_hoa_mang;
                        //$nv_tien_dau_so = $tien_dau_so;
                        $nv_tien_vat_tu = $tien_vat_tu;
                        $nv_ky_quy = $ky_quy;
                        $nv_tong_cong = $tong_cong;
                    }
                    else{
                        //$nv_phi_hoa_mang += $phi_hoa_mang;
                        //$nv_tien_dau_so += $tien_dau_so;
                        $nv_tien_vat_tu += $tien_vat_tu;
                        $nv_ky_quy += $ky_quy;
                        $nv_tong_cong += $tong_cong;
                    }

                    $gb_row = $gb->get_new_row();
                    $gb_row->add_data(
                        $stt,
                        $employee_name,
                        $record['receipt'],
                        //$record['cable_contract_code'],
                        //$record['internet_contract_code'],
                        date('d-m-Y', strtotime($record['acceptance_date'])),
                        $record['customer_name'],
                        //number_format($phi_hoa_mang, 0, ',', '.'),
                        //number_format($tien_dau_so, 0, ',', '.'),
                        number_format($tien_vat_tu, 0, ',', '.'),
                        number_format($ky_quy, 0, ',', '.'),
                        number_format($tong_cong, 0, ',', '.')
                    );
                }

                if($prev_name != null){
                    $gb_row = $gb->get_new_row();
                    $gb_row->add_data(
                        null,
                        //null,
                        //null,
                        null,
                        null,
                        null,
                        '<strong>TỔNG</strong>',
                        //'<strong>'.number_format($nv_phi_hoa_mang, 0, ',', '.').'<strong>',
                        //'<strong>'.number_format($nv_tien_dau_so, 0, ',', '.').'<strong>',
                        '<strong>'.number_format($nv_tien_vat_tu, 0, ',', '.').'<strong>',
                        '<strong>'.number_format($nv_ky_quy, 0, ',', '.').'<strong>',
                        '<strong>'.number_format($nv_tong_cong, 0, ',', '.').'<strong>'
                    );
                }

                $gb_row = $gb->get_new_row();
                $gb_row->add_data(
                    null,
                    //null,
                    //null,
                    null,
                    null,
                    null,
                    '<strong>TỔNG CỘNG</strong>',
                    //'<strong>'.number_format($tong_phi_hoa_mang, 0, ',', '.').'<strong>',
                    //'<strong>'.number_format($tong_tien_dau_so, 0, ',', '.').'<strong>',
                    '<strong>'.number_format($tong_tien_vat_tu, 0, ',', '.').'<strong>',
                    '<strong>'.number_format($tong_ky_quy, 0, ',', '.').'<strong>',
                    '<strong>'.number_format($tong_tong_cong, 0, ',', '.').'<strong>'
                );

                $this->display_module($gb, array(false),'automatic_display');

                $keymd5 = md5(time());
                $_SESSION[$keymd5] = array(
                    'path'=>$this->get_path()
                );
                $print_href = 'href="modules/SCTV/MaintenanceAcceptance/print_bang_ke_nop_tien_bao_tri.php?'.http_build_query(array('key'=>$keymd5, 'cid'=>CID)).'" target="_blank"';

                Base_ActionBarCommon::add('print', __('Print'), $print_href);
            }
        }
    }
	public function deployment_material_report()
	{
		$manager =  CRM_ContactsCommon::get_my_record();
		$is_area_manager = array_key_exists('area manager', $manager['access']);
		
		$form = $this->init_module('Libs/QuickForm',null,__('Acceptance Report'));
		$form->addElement('datepicker', 'start_date', __('Start Date'));
		$form->addRule('start_date', 'Required', 'required');
		$form->addElement('datepicker', 'end_date', __('End Date'));
		$form->addRule('end_date', 'Required', 'required');
		
		$crists = array('group'=>'Technical'); 
		if($is_area_manager)
			$crists += array('manager'=>$manager['id']);
		
		$form->addElement('autoselect', 'employee', __('Deployment Employee'), array(), array(array('CRM_ContactsCommon','autoselect_contact_suggestbox'), array($crists, array('CRM_ContactsCommon', 'contact_format_default'))), array('CRM_ContactsCommon', 'contact_format_default'), array('style'=>'width:300px'));

        if(!$is_area_manager)
            $form->addElement('autoselect', 'quyettoan', 'Nhân viên quyết toán', array(), array(array('CRM_ContactsCommon','autoselect_contact_suggestbox'), array($crists, array('CRM_ContactsCommon', 'contact_format_default'))), array('CRM_ContactsCommon', 'contact_format_default'), array('style'=>'width:300px'));
		
		$optiongroup = SCTV_MaintenanceGroupCommon::get_maintenance_group();
		$form->addElement('select', 'maintenance_group', __('Maintenance Group'), $optiongroup);
		
		$form->addElement('submit','submit_button',__('Show'));
				
		if ($form->validate()) {
			$filters = $form->exportValues();								
		}
		else {
			$today = date('Y-m-d');
			$filters = array('start_date'=>$today, 'end_date'=>$today);
		}
		
		$form->setDefaults($filters);		
		$form->display_as_row();
			
		if(isset($_REQUEST['submited']))
		{
			if(isset($_REQUEST['maintenance_group'])) $this->set_module_variable('maintenance_group', $_REQUEST['maintenance_group']);
			if(isset($_REQUEST['start_date'])) $this->set_module_variable('start_date', $_REQUEST['start_date']);
			if(isset($_REQUEST['end_date'])) $this->set_module_variable('end_date', $_REQUEST['end_date']);

			if(isset($_REQUEST['employee'])) $this->set_module_variable('employee', $_REQUEST['employee']);
            else{
                $this->set_module_variable('employee', null);
            }

            if(isset($_REQUEST['quyettoan'])) $this->set_module_variable('quyettoan', $_REQUEST['quyettoan']);
			else{
                $this->set_module_variable('quyettoan', null);
            }
		}
						
		if($this->isset_module_variable('start_date'))
		{
			$maintenance_group = $this->get_module_variable('maintenance_group');
			$start_date = $this->get_module_variable('start_date');
			$start_date = date('Y-m-d', strtotime($start_date));			
			$end_date = $this->get_module_variable('end_date');	
			$end_date = date('Y-m-d', strtotime($end_date));
			$employee = $this->get_module_variable('employee');
			if($employee == null)
			{
				$employee_is_null = true;
				$employee=0;
			}
			else
			{
				$employee_is_null = false;
			}

            if(!$is_area_manager){
                $quyettoan = $this->get_module_variable('quyettoan');
                if($quyettoan == null){
                }
                else{
                    $is_area_manager = true;
					$manager = CRM_ContactsCommon::get_contact($quyettoan);
                }
            }
						
			$sql = "
				select distinct sctv_material_data_1.id, sctv_material_data_1.f_excel_ordinary_ordinal excel_ordinary_ordinal, sctv_material_data_1.f_excel_free_ordinal excel_free_ordinal, 
				sctv_maintenanceacceptancematerial_data_1.f_material_type material_type, 
				sctv_material_data_1.f_material_code material_code, sctv_material_data_1.f_material_name material_name
				from sctv_material_data_1 
				left join sctv_maintenanceacceptancematerial_data_1 on sctv_maintenanceacceptancematerial_data_1.f_material = sctv_material_data_1.id and
					(sctv_material_data_1.f_excel_ordinary_ordinal = 0 or sctv_material_data_1.f_excel_free_ordinal = 0) and
					(sctv_maintenanceacceptancematerial_data_1.f_material_type <= 1) and   
					sctv_maintenanceacceptancematerial_data_1.f_maintenanceacceptance in
						(
							select id
							from sctv_maintenanceacceptance_data_1
							where sctv_maintenanceacceptance_data_1.active = 1 and
								(%b = false or sctv_maintenanceacceptance_data_1.created_by = %d) and
								f_maintenance in
								(
									select id
									from sctv_maintenance_data_1
									where sctv_maintenance_data_1.active = 1 and sctv_maintenance_data_1.f_status = '1' and
										(%b = true or sctv_maintenance_data_1.f_deployment_employee = %d) and
										sctv_maintenance_data_1.f_acceptance_date between %D and %D
								) 
						)
				where
					(sctv_material_data_1.f_excel_ordinary_ordinal > 0 or sctv_material_data_1.f_excel_free_ordinal > 0) 
					or
					(
						sctv_maintenanceacceptancematerial_data_1.active = 1 and
					  	sctv_maintenanceacceptancematerial_data_1.f_material_type <= 1 and
						f_maintenanceacceptance in
						(
							select id
							from sctv_maintenanceacceptance_data_1
							where sctv_maintenanceacceptance_data_1.active = 1 and
								(%b = false or sctv_maintenanceacceptance_data_1.created_by = %d) and
								f_maintenance in
								(
									select id
									from sctv_maintenance_data_1
									where sctv_maintenance_data_1.active = 1 and sctv_maintenance_data_1.f_status = '1' and
										(%b = true or sctv_maintenance_data_1.f_deployment_employee = %d) and
										sctv_maintenance_data_1.f_acceptance_date between %D and %D
								) 
						)
					)
				order by sctv_material_data_1.f_excel_ordinary_ordinal desc, sctv_material_data_1.f_excel_free_ordinal desc
			";
			
			$records = DB::GetAll($sql, array($is_area_manager, $manager['login'], $employee_is_null, $employee, $start_date, $end_date,$is_area_manager, $manager['login'], $employee_is_null, $employee, $start_date, $end_date));
			//print_r($records);
			
						
			$columns_index = array();
			$columns = array(
				array('name'=>__('STT'), 'width'=>'30px'),
				array('name'=>__('Receipt'), 'width'=>'50px'),
				array('name'=>__('Maintenance Code'), 'width'=>'50px'),
				//array('name'=>__('Cable Contract Code'), 'width'=>'50px'),
				//array('name'=>__('Internet Contract Code'), 'width'=>'50px'),
				array('name'=>__('Customer Code'), 'width'=>'40px'),
				array('name'=>__('Customer Name'), 'width'=>'120px'),
				array('name'=>__('Address'), 'width'=>'150px'),				
				array('name'=>__('Maintenance Date'), 'width'=>'70px'),	
				array('name'=>__('Acceptance Date'), 'width'=>'70px'),				
				array('name'=>__('Số tiền'), 'width'=>'80px'),
				//array('name'=>'<div>'.__('Phí hòa mạng, Phí di dời, chuyển nhượng').'</div>', 'width'=>'80px'),
				//array('name'=>__('Bán đầu số'), 'width'=>'80px'),
				array('name'=>__('Bán vật tư'), 'width'=>'80px'),
				array('name'=>__('Ký quỹ'), 'width'=>'80px'),
			);
			
			$index = count($columns);					
			
			foreach ($records as $record) {
				if($record['excel_ordinary_ordinal'] > 0 && $record['material_type'] == 0)
				{
					$price_istvbox = SCTV_MaterialCommon::get_current_price_istvbox($record['id'], $end_date);
					$columns[] = array('name'=>$record['material_name'] . '<br>' . $record['material_code'] . '<br>' . Utils_CurrencyFieldCommon::format($price_istvbox['price']), 'width'=>'60px', 'nowrap'=>'0');	
															
					$columns_index += array($record['id'] . '_0'=>$index);
				
					$index++;
				}			
			}
			
			foreach ($records as $record) {
				if($record['excel_free_ordinal'] > 0)
				{
					$columns[] = array('name'=>$record['material_name'] . '<br>' . $record['material_code'] . '<br>Miễn phí', 'width'=>'60px', 'nowrap'=>'0');
						
					$columns_index += array($record['id'] . '_1'=>$index);
				
					$index++;
				}
			}
			
			$midle_index = $index;
			//$columns[] = array('name'=>__('Gói cước'), 'width'=>'80px');$index++;			
			//$columns[] = array('name'=>__('Nghiệp vụ'), 'width'=>'120px');$index++;
			$columns[] = array('name'=>__('Ghi chú'), 'width'=>'120px');$index++;
			$columns[] = array('name'=>__('Người lắp'), 'width'=>'120px');$index++;
			$columns[] = array('name'=>__('Nhân viên quyết toán'), 'width'=>'120px');$index++;
			
			// Vat tu khac
			foreach ($records as $record) {
				if($record['excel_ordinary_ordinal'] == 0 && $record['material_type'] == 0)				
				{
					$price_istvbox = SCTV_MaterialCommon::get_current_price_istvbox($record['id'], $end_date);
					$columns[] = array('name'=>$record['material_name'] . '<br>' . $record['material_code'] . '<br>' . Utils_CurrencyFieldCommon::format($price_istvbox['price']), 'width'=>'60px', 'nowrap'=>'0');	
				
					$columns_index += array($record['id'] . '_' . $record['material_type']=>$index);
				
					$index++;
				}
				
				if($record['excel_free_ordinal'] == 0 && $record['material_type'] == 1)				
				{
					$columns[] = array('name'=>$record['material_name'] . '<br>' . $record['material_code'], 'width'=>'60px', 'nowrap'=>'0');

					$columns_index += array($record['id'] . '_' . $record['material_type']=>$index);
				
					$index++;
				}
			}
								
			$default_row[] = array();
			for($i = 0; $i < count($columns)-1; $i++)
				$default_row[] = '';
			$summary_row = $default_row; 
			//print_r($columns);
			//print_r($columns_index);
			//print_r($default_row);
			//return;
			
			$gb = $this->init_module('Utils/GenericBrowser',null,'acceptance_report');
			$gb->set_table_columns($columns);					
			
			$stt = 1;
			$crists = array('status'=>1, '>=acceptance_date'=>$start_date, '<=acceptance_date'=>$end_date);
			if(!$employee_is_null)
			 	$crists += array('deployment_employee'=>$employee);

			if($maintenance_group != null)
				$crists += array('maintenance_group'=>$maintenance_group);
			
			$maintenances = Utils_RecordBrowserCommon::get_records('SCTV_Maintenance', $crists, array(), array('acceptance_date'=>'ASC'));
			
			foreach ($maintenances as $maintenance_id => $maintenance)
			{
                $href = null;
				$acceptances = Utils_RecordBrowserCommon::get_records('SCTV_MaintenanceAcceptance', array('maintenance'=>$maintenance_id));
				foreach ($acceptances as $acceptance_id => $acceptance)
				{
					if($acceptance['created_by'] != $manager['login'] && $is_area_manager) continue;

					$materials = Utils_RecordBrowserCommon::get_records('SCTV_MaintenanceAcceptanceMaterial', array('maintenanceacceptance'=>$acceptance_id, '<=material_type'=>1), array());					
					$row = $default_row;
					$row[0] =  $stt;
					$stt++;
					
					$row[1] =  $acceptance['receipt'];

                    if($acceptance['checked'] != 1)
                        $href = Utils_RecordBrowserCommon::create_record_href('SCTV_Maintenance', $maintenance_id);

                    if($href == null)
					    $row[2] = $maintenance['maintenance_code'];
                    else
                        $row[2] = '<a ' . $href .'>'.$maintenance['maintenance_code'].'</a>';
					
					//$row[3] = $maintenance['cable_contract_code'];
					//$row[4] = $maintenance['internet_contract_code'];
					$row[3] = $maintenance['customer_code'];
					$row[4] = $acceptance['customer_name'];
					$row[5] = $acceptance['address'];
					$row[6] = date('d-m-Y', strtotime($maintenance['maintenance_date']));
					$row[7] = date('d-m-Y', strtotime($maintenance['acceptance_date']));
					//$row[10] = 999;
					//$fee = $acceptance['fee'];
                    //$row[11] = number_format($fee, 0, ',', '.');
					//$summary_row[11] += $fee;
					//$row[12] = 999;
					//$row[13] = 999;
					$deposit = $acceptance['deposit'];
					$row[10] = number_format($deposit, 0, ',', '.');
					$summary_row[10] += $deposit;
					
					$summary_tvbox = 0;
					$summary_material = 0;
					foreach ($materials as $acceptance_material_id => $acceptance_material)
					{
						$xxx_index = $columns_index[$acceptance_material['material'] . '_' . $acceptance_material['material_type']];

						$amount = $acceptance_material['amount'];
																													
						$row[$xxx_index] = $amount;
						$summary_row[$xxx_index] += $amount;
						
						if($acceptance_material['material_type'] == 0)
						{
							$istvbox = Utils_RecordBrowserCommon::get_value('SCTV_Material', $acceptance_material['material'], 'istvbox');
							if($istvbox == 1)
							{
								$summary_tvbox += $acceptance_material['total'];
							}
							else 
							{
								$summary_material += $acceptance_material['total'];
							}
							
						}
					}
					
					//$sum_all = $fee + $deposit + $summary_tvbox + $summary_material;
					$sum_all = $deposit + $summary_tvbox + $summary_material;
					$row[8] = number_format($sum_all, 0, ',', '.');
					$summary_row[8] += $sum_all;
					//$row[12] = number_format($summary_tvbox, 0, ',', '.');
					//$summary_row[12] += $summary_tvbox;
					$row[9] = number_format($summary_material, 0, ',', '.');
					$summary_row[9] += $summary_material;
																																	
					$new_index = $midle_index;
					/*if(empty($maintenance['deployment_bundle']))
						$row[$new_index] = null;
					else
						$row[$new_index] = Utils_RecordBrowserCommon::get_value('SCTV_Bundle', $maintenance['deployment_bundle'], 'name');
					$new_index++;
					$row[$new_index] = $maintenance['deployment_business'];					
					$new_index++;*/
					$row[$new_index] = $acceptance['note'];					
					$new_index++;
					$row[$new_index] = CRM_ContactsCommon::contact_format_no_company($maintenance['deployment_employee'], true);
					$new_index++;
					$contact =  CRM_ContactsCommon::get_contact_by_user_id($acceptance['created_by']);
					$row[$new_index] = CRM_ContactsCommon::contact_format_no_company($contact, true);
					$new_index++;

					$gb_row = $gb->get_new_row();			
					$gb_row->add_data_array($row);
				}
			}

			foreach ($summary_row as $key => $value) {
				if($value != null)
					$summary_row[$key] = '<strong>' . number_format($value, 0, ',', '.') . '</strong>';
			}
			$summary_row[6] = '<strong>Tổng cộng</strong>';
			$gb_row = $gb->get_new_row();	
			$gb_row->add_data_array($summary_row);

			$this->display_module($gb, array(true),'automatic_display');
			
			Base_ActionBarCommon::add('save', __('Export Excel'), 'href="modules/SCTV/MaintenanceAcceptance/excel.php?'.http_build_query(array('cid'=>CID, 'path'=>$this->get_path())).'"');																										
		}
	}
	
	public function subnet_material_report()
	{
		$manager =  CRM_ContactsCommon::get_my_record();
		$is_area_manager = array_key_exists('area manager', $manager['access']);
		
		$form = $this->init_module('Libs/QuickForm',null,__('Maintenance Acceptance Report'));
		$form->addElement('datepicker', 'start_date', __('Start Date'));
		$form->addRule('start_date', 'Required', 'required');
		$form->addElement('datepicker', 'end_date', __('End Date'));
		$form->addRule('end_date', 'Required', 'required');
		
		$form->addElement('submit','submit_button',__('Show'));
				
		if ($form->validate()) {
			$filters = $form->exportValues();								
		}
		else {
			$today = date('Y-m-d');
			$filters = array('start_date'=>$today, 'end_date'=>$today);
		}
		
		$form->setDefaults($filters);		
		$form->display_as_row();
			
		if(isset($_REQUEST['submited']))
		{
			if(isset($_REQUEST['start_date'])) $this->set_module_variable('start_date', $_REQUEST['start_date']);
			if(isset($_REQUEST['end_date'])) $this->set_module_variable('end_date', $_REQUEST['end_date']);					
		}
						
		if($this->isset_module_variable('start_date'))
		{
			$start_date = $this->get_module_variable('start_date');
			$start_date = date('Y-m-d', strtotime($start_date));			
			$end_date = $this->get_module_variable('end_date');	
			$end_date = date('Y-m-d', strtotime($end_date));
						
			$sql = "
				select distinct sctv_material_data_1.id, sctv_material_data_1.f_excel_subnet_ordinal excel_subnet_ordinal, 
				sctv_material_data_1.f_material_code material_code, sctv_material_data_1.f_material_name material_name
				from sctv_material_data_1 
				left join sctv_maintenanceacceptancematerial_data_1 on sctv_maintenanceacceptancematerial_data_1.f_material = sctv_material_data_1.id and
					sctv_material_data_1.f_excel_subnet_ordinal = 0 and
					f_maintenanceacceptance in
						(
							select id
							from sctv_maintenanceacceptance_data_1
							where sctv_maintenanceacceptance_data_1.active = 1 and
								(%b = false or sctv_maintenanceacceptance_data_1.created_by = %d) and
								f_maintenance in
								(
									select id
									from sctv_maintenance_data_1
									where sctv_maintenance_data_1.active = 1 and sctv_maintenance_data_1.f_status = '1' and
										sctv_maintenance_data_1.f_acceptance_date between %D and %D
								) 
						)   
				where
					(sctv_material_data_1.f_excel_subnet_ordinal > 0) 
					or
					(
						sctv_maintenanceacceptancematerial_data_1.active = 1 and
					  	sctv_maintenanceacceptancematerial_data_1.f_material_type > 1 and
						f_maintenanceacceptance in
						(
							select id
							from sctv_maintenanceacceptance_data_1
							where sctv_maintenanceacceptance_data_1.active = 1 and
								(%b = false or sctv_maintenanceacceptance_data_1.created_by = %d) and
								f_maintenance in
								(
									select id
									from sctv_maintenance_data_1
									where sctv_maintenance_data_1.active = 1 and sctv_maintenance_data_1.f_status = '1' and
										sctv_maintenance_data_1.f_acceptance_date between %D and %D
								) 
						)
					)
				order by sctv_material_data_1.f_excel_subnet_ordinal desc
			";
																								
			$records = DB::GetAll($sql, array($is_area_manager, $manager['login'], $start_date, $end_date, $is_area_manager, $manager['login'], $start_date, $end_date));
			
			//print_r($records);
						
			$columns_index = array();
			$columns = array(
				array('name'=>__('STT'), 'width'=>'30px'),
				array('name'=>__('Maintenance Code'), 'width'=>'50px'),
				//array('name'=>__('Cable Contract Code'), 'width'=>'50px'),
				//array('name'=>__('Internet Contract Code'), 'width'=>'50px'),
				array('name'=>__('Customer Code'), 'width'=>'40px'),
				array('name'=>__('Customer Name'), 'width'=>'120px'),
				array('name'=>__('Address'), 'width'=>'150px'),				
				array('name'=>__('Maintenance Date'), 'width'=>'70px'),	
				array('name'=>__('Acceptance Date'), 'width'=>'70px'),				
				array('name'=>__('Số tiền'), 'width'=>'80px')
			);
			
			$index = count($columns);			
			
			foreach ($records as $record) {
				if($record['excel_subnet_ordinal'] > 0)
				{
					$columns[] = array('name'=>$record['material_name'] . '<br>' . $record['material_code'], 'width'=>'60px', 'nowrap'=>'0');	
															
					$columns_index += array($record['id']=>$index);
				
					$index++;
				}			
			}		
			
			$midle_index = $index;
			$columns[] = array('name'=>__('Ghi chú'), 'width'=>'120px');$index++;
			$columns[] = array('name'=>__('Người bảo trì'), 'width'=>'120px');$index++;
			$columns[] = array('name'=>__('Nhân viên quyết toán'), 'width'=>'120px');$index++;
			
			// Vat tu khac
			foreach ($records as $record) {
				if($record['excel_subnet_ordinal'] == 0)
				{									
					$columns[] = array('name'=>$record['material_name'] . '<br>' . $record['material_code'], 'width'=>'60px', 'nowrap'=>'0');
										
					$columns_index += array($record['id']=>$index);
				
					$index++;
				} 
			}
								
			$default_row[] = array();
			for($i = 0; $i < count($columns)-1; $i++)
				$default_row[] = '';
			
			//print_r($columns);
			//print_r($columns_index);
			//print_r($default_row);
			//return;
			
			$gb = $this->init_module('Utils/GenericBrowser',null,'acceptance_report');
			$gb->set_table_columns($columns);					
			
			$stt = 1;
			$maintenances = Utils_RecordBrowserCommon::get_records('SCTV_Maintenance', array('status'=>1, '>=acceptance_date'=>$start_date, '<=acceptance_date'=>$end_date), array(), array('acceptance_date'=>'ASC'));
			foreach ($maintenances as $maintenance_id => $maintenance)
			{
                $href = null;
				$acceptances = Utils_RecordBrowserCommon::get_records('SCTV_MaintenanceAcceptance', array('maintenance'=>$maintenance_id));
				foreach ($acceptances as $acceptance_id => $acceptance)
				{
					if($acceptance['created_by'] != $manager['login'] && $is_area_manager) continue;

					$row = $default_row;
					$row[0] =  $stt;$stt++;

                    if($acceptance['checked'] != 1)
                        $href = Utils_RecordBrowserCommon::create_record_href('SCTV_Maintenance', $maintenance_id);

                    if($href == null)
                        $row[1] = $maintenance['maintenance_code'];
                    else
                        $row[1] = '<a ' . $href .'>'.$maintenance['maintenance_code'].'</a>';

					//$row[2] = $maintenance['cable_contract_code'];
					//$row[3] = $maintenance['internet_contract_code'];
					$row[2] = $maintenance['customer_code'];
					$row[3] = $acceptance['customer_name'];
					$row[4] = $acceptance['address'];
					$row[5] = date('d-m-Y', strtotime($maintenance['maintenance_date']));
					$row[6] = date('d-m-Y', strtotime($maintenance['acceptance_date']));
					$row[7] = 999;
					
					$materials = Utils_RecordBrowserCommon::get_records('SCTV_MaintenanceAcceptanceMaterial', array('maintenanceacceptance'=>$acceptance_id, 'material_type'=>2), array());
					if(!empty($materials))
					{
						foreach ($materials as $acceptance_material_id => $acceptance_material)
						{						
							$row[$columns_index[$acceptance_material['material']]] = $acceptance_material['amount'];					
						}
					
						$row[7] = 0; //Utils_CurrencyFieldCommon::format($fee + $deposit + $summary_tvbox + $summary_material);
																																	
						$new_index = $midle_index;
						$row[$new_index] = $acceptance['note'];					
						$new_index++;
						$contact =  CRM_ContactsCommon::get_contact($maintenance['deployment_employee']);						
						$row[$new_index] = CRM_ContactsCommon::contact_format_no_company($contact);
						$new_index++;						
						$contact =  CRM_ContactsCommon::get_contact_by_user_id($acceptance['created_by']);
						$row[$new_index] = CRM_ContactsCommon::contact_format_no_company($contact);
						$new_index++;
					
						//print_r($row);
						//echo '<br/>';
						//return;
					
					
						$gb_row = $gb->get_new_row();			
						$gb_row->add_data_array($row);
					}
				}
			}

			$this->display_module($gb, array(false),'automatic_display');
			
			Base_ActionBarCommon::add('save', __('Export Excel'), 'href="modules/SCTV/MaintenanceAcceptance/subnet_excel.php?'.http_build_query(array('cid'=>CID, 'path'=>$this->get_path())).'"');																										
		}
	}
	
    public function bien_ban_quyet_toan() {
        $tb = $this->init_module('Utils/TabbedBrowser');
        $tb->set_tab('Tổng', array($this, 'bien_ban_quyet_toan_tong'));
        $tb->set_tab('Miễn phí', array($this, 'bien_ban_quyet_toan_mien_phi'));
        $tb->set_tab('Thu tiền', array($this, 'bien_ban_quyet_toan_thu_tien'));
        $tb->set_tab('Mạng phụ', array($this, 'bien_ban_quyet_toan_mang_phu'));
        $this->display_module($tb);
        $tb->tag();
    }
    public function bien_ban_quyet_toan_tong(){
        $this->tham_so_bao_cao('Biên bản quyết toán vật tư(Tổng)', 'bien_ban_quyet_toan_vat_tu_tong');

        if($this->isset_module_variable('bien_ban_quyet_toan_vat_tu_tong_start_date'))
        {
            $start_date = $this->get_module_variable('bien_ban_quyet_toan_vat_tu_tong_start_date');
            $start_date = date('Y-m-d', strtotime($start_date));
            $end_date = $this->get_module_variable('bien_ban_quyet_toan_vat_tu_tong_end_date');
            $end_date = date('Y-m-d', strtotime($end_date));
            $employee = $this->get_module_variable('bien_ban_quyet_toan_vat_tu_tong_truong_khu_vuc');
			$group = $this->get_module_variable('bien_ban_quyet_toan_vat_tu_tong_group');
			if($group == null){
				$group_is_null = true;
				$group = 0;
			}
			else{
				$group_is_null = false;
			}

            if(!empty($employee)){
                $records = DB::GetAll('select * from sctv_bien_ban_quyet_toan_tong_baotri(%D, %D, %d, %b, %d)', array($start_date, $end_date, $employee, $group_is_null, $group));

                $gb = $this->init_module('Utils/GenericBrowser',null,'Bien ban quyet toan vat tu tong');
                $columns = array(
                    array('name'=>__('STT'), 'width'=>'8'),
                    array('name'=>__('Mã vật tư'), 'width'=>'15'),
                    array('name'=>__('Tên vật tư'), 'width'=>'25'),
                    array('name'=>__('ĐVT'), 'width'=>'10'),
                    array('name'=>__('Thu tiền'), 'width'=>'15'),
                    array('name'=>__('Miễn phí'), 'width'=>'15'),
                    array('name'=>__('Mạng phụ'), 'width'=>'15')
                );
                $gb->set_table_columns($columns);
                $stt = 0;
                foreach($records as $key=>$record){
                    $stt++;
                    $gb_row = $gb->get_new_row();
                    $gb_row->add_data($stt, $record['material_code'], $record['material_name'], $record['material_unit'], $record['thu_tien'], $record['mien_phi'], $record['mang_phu']);
                }

                $this->display_module($gb, array(false),'automatic_display');

                $keymd5 = md5(time());
                $_SESSION[$keymd5] = array(
                    'path'=>$this->get_path()
                );
                $print_href = 'href="modules/SCTV/MaintenanceAcceptance/print_bien_ban_quyet_toan_tong.php?'.http_build_query(array('key'=>$keymd5, 'cid'=>CID)).'" target="_blank"';

                Base_ActionBarCommon::add('print', __('Print'), $print_href);
            }
        }
    }
    public function bien_ban_quyet_toan_mien_phi(){
        $this->tham_so_bao_cao('Biên bản quyết toán vật tư(Miễn phí)', 'bien_ban_quyet_toan_vat_tu_mien_phi');

        if($this->isset_module_variable('bien_ban_quyet_toan_vat_tu_mien_phi_start_date'))
        {
            $start_date = $this->get_module_variable('bien_ban_quyet_toan_vat_tu_mien_phi_start_date');
            $start_date = date('Y-m-d', strtotime($start_date));
            $end_date = $this->get_module_variable('bien_ban_quyet_toan_vat_tu_mien_phi_end_date');
            $end_date = date('Y-m-d', strtotime($end_date));
            $employee = $this->get_module_variable('bien_ban_quyet_toan_vat_tu_mien_phi_truong_khu_vuc');
			$group = $this->get_module_variable('bien_ban_quyet_toan_vat_tu_mien_phi_group');
			if($group == null){
				$group_is_null = true;
				$group = 0;
			}
			else{
				$group_is_null = false;
			}

            if(!empty($employee)){
                $records = DB::GetAll('select * from sctv_bien_ban_quyet_toan_mien_phi_bao_tri(%D, %D, %d, %b, %d)', array($start_date, $end_date, $employee, $group_is_null, $group));

                $gb = $this->init_module('Utils/GenericBrowser',null,'Bien ban quyet toan vat tu mien phi');
                $columns = array(
                    array('name'=>__('STT'), 'width'=>'8'),
                    array('name'=>__('Mã vật tư'), 'width'=>'15'),
                    array('name'=>__('Tên vật tư'), 'width'=>'25'),
                    array('name'=>__('ĐVT'), 'width'=>'10'),
                    array('name'=>__('Số lượng'), 'width'=>'15')
                );
                $gb->set_table_columns($columns);
                $stt = 0;
                foreach($records as $key=>$record){
                    $stt++;
                    $gb_row = $gb->get_new_row();
                    $gb_row->add_data($stt, $record['material_code'], $record['material_name'], $record['material_unit'], $record['mien_phi']);
                }

                $this->display_module($gb, array(false),'automatic_display');

                $keymd5 = md5(time());
                $_SESSION[$keymd5] = array(
                    'path'=>$this->get_path()
                );
                $print_href = 'href="modules/SCTV/MaintenanceAcceptance/print_bien_ban_quyet_toan_mien_phi.php?'.http_build_query(array('key'=>$keymd5, 'cid'=>CID)).'" target="_blank"';

                Base_ActionBarCommon::add('print', __('Print'), $print_href);
            }
        }
    }
    public function bien_ban_quyet_toan_thu_tien(){
        $this->tham_so_bao_cao('Biên bản quyết toán vật tư(Thu tiền)', 'bien_ban_quyet_toan_vat_tu_thu_tien');

        if($this->isset_module_variable('bien_ban_quyet_toan_vat_tu_thu_tien_start_date'))
        {
            $start_date = $this->get_module_variable('bien_ban_quyet_toan_vat_tu_thu_tien_start_date');
            $start_date = date('Y-m-d', strtotime($start_date));
            $end_date = $this->get_module_variable('bien_ban_quyet_toan_vat_tu_thu_tien_end_date');
            $end_date = date('Y-m-d', strtotime($end_date));
            $employee = $this->get_module_variable('bien_ban_quyet_toan_vat_tu_thu_tien_truong_khu_vuc');
			$group = $this->get_module_variable('bien_ban_quyet_toan_vat_tu_thu_tien_group');
			if($group == null){
				$group_is_null = true;
				$group = 0;
			}
			else{
				$group_is_null = false;
			}

            if(!empty($employee)){
                $records = DB::GetAll('select * from sctv_bien_ban_quyet_toan_thu_tien_bao_tri(%D, %D, %d, %b, %d)', array($start_date, $end_date, $employee, $group_is_null, $group));

                $gb = $this->init_module('Utils/GenericBrowser',null,'Bien ban quyet toan vat tu thu tien');
                $columns = array(
                    array('name'=>__('STT'), 'width'=>'8'),
                    array('name'=>__('Mã vật tư'), 'width'=>'15'),
                    array('name'=>__('Tên vật tư'), 'width'=>'25'),
                    array('name'=>__('ĐVT'), 'width'=>'10'),
                    array('name'=>__('Số lượng'), 'width'=>'15')
                );
                $gb->set_table_columns($columns);
                $stt = 0;
                foreach($records as $key=>$record){
                    $stt++;
                    $gb_row = $gb->get_new_row();
                    $gb_row->add_data($stt, $record['material_code'], $record['material_name'], $record['material_unit'], $record['thu_tien']);
                }

                $this->display_module($gb, array(false),'automatic_display');

                $keymd5 = md5(time());
                $_SESSION[$keymd5] = array(
                    'path'=>$this->get_path()
                );
                $print_href = 'href="modules/SCTV/MaintenanceAcceptance/print_bien_ban_quyet_toan_thu_tien.php?'.http_build_query(array('key'=>$keymd5, 'cid'=>CID)).'" target="_blank"';

                Base_ActionBarCommon::add('print', __('Print'), $print_href);
            }
        }
    }
    public function bien_ban_quyet_toan_mang_phu(){
        $this->tham_so_bao_cao('Biên bản quyết toán vật tư(Mạng phụ)', 'bien_ban_quyet_toan_vat_tu_mang_phu');

        if($this->isset_module_variable('bien_ban_quyet_toan_vat_tu_mang_phu_start_date'))
        {
            $start_date = $this->get_module_variable('bien_ban_quyet_toan_vat_tu_mang_phu_start_date');
            $start_date = date('Y-m-d', strtotime($start_date));
            $end_date = $this->get_module_variable('bien_ban_quyet_toan_vat_tu_mang_phu_end_date');
            $end_date = date('Y-m-d', strtotime($end_date));
            $employee = $this->get_module_variable('bien_ban_quyet_toan_vat_tu_mang_phu_truong_khu_vuc');
			$group = $this->get_module_variable('bien_ban_quyet_toan_vat_tu_mang_phu_group');
			if($group == null){
				$group_is_null = true;
				$group = 0;
			}
			else{
				$group_is_null = false;
			}

            if(!empty($employee)){
                $records = DB::GetAll('select * from sctv_bien_ban_quyet_toan_mang_phu_bao_tri(%D, %D, %d, %b, %d)', array($start_date, $end_date, $employee, $group_is_null, $group));

                $gb = $this->init_module('Utils/GenericBrowser',null,'Bien ban quyet toan vat tu mang phu');
                $columns = array(
                    array('name'=>__('STT'), 'width'=>'8'),
                    array('name'=>__('Mã vật tư'), 'width'=>'15'),
                    array('name'=>__('Tên vật tư'), 'width'=>'25'),
                    array('name'=>__('ĐVT'), 'width'=>'10'),
                    array('name'=>__('Số lượng'), 'width'=>'15')
                );
                $gb->set_table_columns($columns);
                $stt = 0;
                foreach($records as $key=>$record){
                    $stt++;
                    $gb_row = $gb->get_new_row();
                    $gb_row->add_data($stt, $record['material_code'], $record['material_name'], $record['material_unit'], $record['mang_phu']);
                }

                $this->display_module($gb, array(false),'automatic_display');

                $keymd5 = md5(time());
                $_SESSION[$keymd5] = array(
                    'path'=>$this->get_path()
                );
                $print_href = 'href="modules/SCTV/MaintenanceAcceptance/print_bien_ban_quyet_toan_mang_phu.php?'.http_build_query(array('key'=>$keymd5, 'cid'=>CID)).'" target="_blank"';

                Base_ActionBarCommon::add('print', __('Print'), $print_href);
            }
        }
    }
	private $theme;
	private $values;
	public function material_addon($arg){
		$rb = $this->init_module('Utils/RecordBrowser','SCTV_MaintenanceAcceptanceMaterial');
		$rb->disable_actions();
			$rb->disable_pdf();
			$rb->disable_export();
			$rb->disable_filters();
			$rb->disable_search();
			$rb->disable_jump_to_record();			
		$rpm = array(array('maintenanceacceptance'=>$arg['id']), array(), array());
		$this->display_module($rb,$rpm,'show_data');
	}
  	public function maintenance_acceptance_addon($arg){  		
  		if(empty($arg['acceptance_date'])) return;
				
  		$maintenance = $arg['id'];
		$acceptances = Utils_RecordBrowserCommon::get_records('SCTV_MaintenanceAcceptance', array('maintenance'=>$maintenance), array(), array(), array(), true);
		if(!empty($acceptances))
		{
			$acceptance = array_shift($acceptances);
		}
		
		$prompt_id = "new_document";			
        $content = $this->new_form($prompt_id, $arg, $acceptance);		
        Libs_LeightboxCommon::display($prompt_id, $content, __('Deployment Material') . ' #' . $maintenance . ' : ' . $arg['deployment_business'], 1);
			
		if(!empty($this->values) && $this->values['submited'] == 1)
		{					
			$id = Utils_RecordBrowserCommon::get_id('SCTV_MaintenanceAcceptance', 'maintenance', $maintenance);
			if($id == null)
			{
				$id = Utils_RecordBrowserCommon::new_record('SCTV_MaintenanceAcceptance', array(
					'maintenance'=>$maintenance,
					'customer_name'=>$this->values['customer'],
					'address'=>$this->values['address'],
					'receipt'=>$this->values['receipt'],
					'fee'=>$this->values['fee'],
					'deposit'=>$this->values['deposit'],
					'note'=>$this->values['note'],
					'checked'=>0
				));
			}
			else {
				Utils_RecordBrowserCommon::update_record('SCTV_MaintenanceAcceptance', $id, array(
					'maintenance'=>$maintenance,
					'customer_name'=>$this->values['customer'],
					'address'=>$this->values['address'],
					'receipt'=>$this->values['receipt'],
					'fee'=>$this->values['fee'],
					'deposit'=>$this->values['deposit'],
					'note'=>$this->values['note']
				));
			}
			
			DB::Execute('DELETE FROM sctv_maintenanceacceptancematerial_data_1 WHERE f_maintenanceacceptance=%d', array($id));
			
			foreach ($this->values['free'] as $key => $values) {
				if(!empty($values['material']) && !empty($values['amount']))
				{
					Utils_RecordBrowserCommon::new_record('SCTV_MaintenanceAcceptanceMaterial', 
						array(
							'maintenanceacceptance'=>$id, 
							'material'=>$values['material'],
							'material_type'=>1,
							'amount'=>$values['amount'],
							'price'=>0,
							'total'=>0
						));
				}
			}
			
			foreach ($this->values['subnet'] as $key => $values) {
				if(!empty($values['material']) && !empty($values['amount']))
				{
					Utils_RecordBrowserCommon::new_record('SCTV_MaintenanceAcceptanceMaterial', 
						array(
							'maintenanceacceptance'=>$id, 
							'material'=>$values['material'],
							'material_type'=>2,
							'amount'=>$values['amount'],
							'price'=>0,
							'total'=>0
						));
				}
			}
			
			foreach ($this->values['charge'] as $key => $values) {
				if(!empty($values['material']) && !empty($values['amount']) && $values['amount'] > 0)
				{
					Utils_RecordBrowserCommon::new_record('SCTV_MaintenanceAcceptanceMaterial', 
						array(
							'maintenanceacceptance'=>$id, 
							'material'=>$values['material'],
							'material_type'=>0,
							'amount'=>$values['amount'],
							'price'=>$values['price'],
							'total'=>$values['total']
						));
				}
			}
			
			location(array());
		}
		
																				      
		$form = & $this->init_module('Libs/QuickForm');
		if($acceptance == null)
		{
			if(Utils_RecordBrowserCommon::get_access('SCTV_MaintenanceAcceptance', 'edit'))
				$submit = $form->addElement('button', 'add_new', __('Add Maintenance Acceptance Material'), Libs_LeightboxCommon::get_open_href($prompt_id));
			
			$form->display();				
		}
		else
		{
			$rb = $this->init_module('Utils_RecordBrowser', 'SCTV_MaintenanceAcceptance');
			$rb->disable_actions();
			$rb->disable_pdf();
			$rb->disable_export();
			$rb->disable_filters();
			$rb->disable_search();
			$rb->disable_jump_to_record();
			$rb->disable_headline();
			$rb->disable_quickjump();
			$id = explode('_',$id);
			$this->display_module($rb, array('view', $acceptance['id'], array(), array()), 'view_entry'); 
			
			$fee = $acceptance['fee'];
			$deposit = $acceptance['deposit'];
								
			$summary_tvbox = 0;
			$summary_material = 0;
			
			$materials = Utils_RecordBrowserCommon::get_records('SCTV_MaintenanceAcceptanceMaterial', array('maintenanceacceptance'=>$acceptance['id']));
			foreach ($materials as $key => $material) {
				if($material['material_type'] == 0)
				{
					$istvbox = Utils_RecordBrowserCommon::get_value('SCTV_Material', $material['material'], 'istvbox');
					if($istvbox == 1)
					{
						$summary_tvbox += $material['total'];
					}
					else 
					{
						$summary_material += $material['total'];
					}
				}
			}
				
				/*						
			$rb = $this->init_module('Utils/RecordBrowser','SCTV_AcceptanceMaterial');
			$rb->disable_actions();
			$rb->disable_pdf();
			$rb->disable_export();
			$rb->disable_filters();
			$rb->disable_search();		
			$acceptanceMaterial = array(array('acceptance'=>$acceptance['id']), array(), array());
			$this->display_module($rb,$acceptanceMaterial,'show_data');*/
			
			$summary_tvbox_formatted = Utils_CurrencyFieldCommon::format($summary_tvbox);
			$summary_tvbox_formatted = str_replace('&nbsp;', ' ', $summary_tvbox_formatted);
			$form->addElement('text', 'view_summary_tvbox', __('TV Box'), array('value'=>$summary_tvbox_formatted, 'readonly'=>true));		
			
			$summary_material_formatted = Utils_CurrencyFieldCommon::format($summary_material);
			$summary_material_formatted = str_replace('&nbsp;', ' ', $summary_material_formatted);
			$form->addElement('text', 'view_summary_material', __('Material'), array('value'=>$summary_material_formatted, 'readonly'=>true));			
			
			$summary_formatted = Utils_CurrencyFieldCommon::format($fee + $deposit + $summary_tvbox + $summary_material);
			$summary_formatted = str_replace('&nbsp;', ' ', $summary_formatted);
			$form->addElement('text', 'view_summary', __('Summary'), array('value'=>$summary_formatted, 'readonly'=>true));
			
			if(Utils_RecordBrowserCommon::get_access('SCTV_MaintenanceAcceptance', 'edit') && $acceptance['checked'] == false)
				$submit = $form->addElement('button', 'add_new', __('Edit'), Libs_LeightboxCommon::get_open_href($prompt_id));			

			$form->display_as_row();

            $form = & $this->init_module('Libs/QuickForm');
            $form->addElement('html', '<hr><h2>Yêu cầu sửa đổi thông tin nghiệm thu</h2>');
            $form->display();

            $area_manager = CRM_ContactsCommon::get_contact_by_user_id($acceptance['created_by']);

			$rb = $this->init_module('Utils/RecordBrowser','SCTV_MaintenanceAcceptanceChangeRequest');
            $rb->disable_actions();
            $rb->disable_pdf();
            $rb->disable_export();
            $rb->disable_filters();
            $rb->disable_search();
            $rb->disable_jump_to_record();
            $rb->set_defaults(array('maintenance'=>$maintenance, 'status'=>0, 'employee'=>$area_manager['id']));
            $rpm = array(array('maintenance'=>$maintenance), array('maintenance'=>false, 'employee'=>false), array());
            $this->display_module($rb,$rpm,'show_data');
			echo '<br><br><br>';
		}									 
	}

	public function new_form($prompt_id, $maintenance, $acceptance)
	{
		$form = $this->init_module('Libs/QuickForm');		
		$theme = Base_ThemeCommon::init_smarty();
		 //$theme = $this->init_module('Base/Theme');		
		
		$defaults = array();
		
		$form->addElement('text', 'customer', __('Customer'));
		$form->addRule('customer','required','required');
		
		$form->addElement('text', 'address', __('Address'));
		$form->addRule('address','required','required');
  				
		$form->addElement('text', 'receipt', __('Receipt'));				
		
		$valid_amount_as_number = "
			var amount = jQuery(this).val();
			if(isNaN(amount) || +amount < 0)
			{
				jQuery(this).text('0');
				jQuery(this).val(0);				
			}
		";
		$summary_js = "
			var fee = jQuery('input[name=\'fee\']').val();
			var deposit = jQuery('input[name=\'deposit\']').val();
			var summary_tvbox = jQuery('input[name=\'summary_tvbox\']').val();
			var summary_material = jQuery('input[name=\'summary_material\']').val();
			jQuery('input[name=\'summary\']').val(+fee + +deposit + +summary_tvbox + +summary_material);
		";		
		
		$form->addElement('text', 'fee', __('Fee'),
			array(
				'onkeyup'=>$valid_amount_as_number . $summary_js,
				'onchange'=>$valid_amount_as_number . $summary_js
			)
		);
		$form->addRule('fee','required','required');
		
		$form->addElement('text', 'deposit', __('Deposit'),
			array(
				'onkeyup'=>$valid_amount_as_number . $summary_js,
				'onchange'=>$valid_amount_as_number . $summary_js
			)
		);
		$form->addRule('deposit','required','required');
		
		$form->addElement('text', 'note', __('Note'));
		
		if($acceptance == null)
			$defaults += array(
				'customer'=>$maintenance['customer_name'], 
				'address'=>$maintenance['address'] . ' ' . Utils_RecordBrowserCommon::get_value('SCTV_Street', $maintenance['street'], 'name'),
				'fee'=>0,
				'deposit'=>0
			);
		else
			$defaults += array(
				'customer'=>$acceptance['customer_name'], 
				'address'=>$acceptance['address'],
				'receipt'=>$acceptance['receipt'],
				'fee'=>$acceptance['fee'],
				'deposit'=>$acceptance['deposit'],
				'note'=>$acceptance['note'],
			);			

		$recs = Utils_RecordBrowserCommon::get_records('SCTV_Material', array('material_free'=>1), array(), array('free_ordinal'=>'DESC'));
		
		$row = 0;
		
		foreach($recs as $rec){
			$default = self::create_free_row($form, $row, $rec['id']);
			$defaults = $defaults + $default;
			
			$row++;
		}
														
		for($i = $row; $i < $row+3; $i++)
		{
			self::create_free_row($form, $i);					
		}
		
		for($i = 0; $i < 5; $i++)
		{
			self::create_subnet_row($form, $i);					
		}
		
		$recs = Utils_RecordBrowserCommon::get_records('SCTV_Material', array('ordinary'=>1), array(), array('ordinary_ordinal'=>'DESC'));			
		
		$row = 0;

		foreach($recs as $rec){
			$default = self::create_charge_row($form, $row, $maintenance['acceptance_date'], $rec['id'], $rec['istvbox']);
			$defaults = $defaults + $default;
			
			$row++;
		}			
				
		for($i = $row; $i < $row+3; $i++)
		{
			self::create_charge_row($form, $i, $maintenance['acceptance_date']);							
		}
		
		$form->addElement('text', 'summary_tvbox', __('Summary TV Box'), 
			array(
				'readonly'=>true,
				'onchange'=>$summary_js
			)
		);
		
		$form->addElement('text', 'summary_material', __('Summary material'), 
			array(
				'readonly'=>true,
				'onchange'=>$summary_js
			)
		);
		
		$defaults += array('summary_tvbox'=>0, 'summary_material'=>0);
		
		$form->addElement('text', 'summary', __('Summary'), array('readonly'=>true));
		
		$form->setDefaults($defaults);
		
		//$submit = $form->addElement('submit', 'submit', 'Submit', array('onclick'=>'leightbox_deactivate("'.$prompt_id.'");', 'class'=>''));
		$theme->assign('just_close',
			array(
				'open'=>'<a id="'.$prefix.'_just_close_button" onclick="leightbox_deactivate(\''.$prompt_id.'\');' . $form->get_submit_form_js(true) . '">',
				'text'=>__( 'Save'),
				'close'=>'</a>'
			)
		);	
		
		$form->assign_theme('form',$theme);		
		
		if ($form->validate())
		{
			$this->values = $form->exportValues();
		}
		else
		{
			$this->values = array();
 			//if($form->exportValue('submited')) Libs_LeightboxCommon::open($prompt_id);
 			//Libs_LeightboxCommon::open($prompt_id);
            // open this selection
            //eval_js('f' . $lb->get_group_key() . '_show_form("close")');
		}			
		
		ob_start(); 
		Base_ThemeCommon::display_smarty($theme,'SCTV_MaintenanceAcceptance','default');		
		$profiles_out = ob_get_clean();
				
        return $profiles_out;						
	}
	private function create_free_row($form, $index, $material_default= null)
	{
		$row = array();		
		$material_element_name = 'free['.$index.'][material]';
		$amount_element_name = 'free['.$index.'][amount]';
		$row[]=$form->createElement(
			'autoselect', 
			$material_element_name, 
			_M('Material'), 
			array(), array(array('SCTV_MaterialCommon','material_suggestbox'), array(array(), array(), array('SCTV_MaterialCommon', 'material_format'))), array('SCTV_MaterialCommon', 'material_format_display'),
			array(
				'onchange'=>"
					if(this.value == '')
					{
						var amount_element = document.getElementsByName('" . $amount_element_name . "')[0]
						amount_element.value = '';
						amount_element.setAttribute('disabled', 'true');						
					}
					else {
						document.getElementsByName('" . $amount_element_name . "')[0].removeAttribute('disabled');
					}						
				"
			)
		);
	    
		
		$valid_amount_as_number = "
			var amount = jQuery('input[name=\'". $amount_element_name ."\']').val();
			if(isNaN(amount) || +amount < 0)
			{
				jQuery('input[name=\'". $amount_element_name ."\']').text('0');
				jQuery('input[name=\'". $amount_element_name ."\']').val(0);				
			}
		";									
		$amount_element=$form->createElement('text', 'free['.$index.'][amount]', __('Amount'),
			array(
				'onchange'=>$valid_amount_as_number				
			)
		);
		
		if($material_default == null)
			$amount_element->setAttribute('disabled', true);
					
		$row[] = $amount_element;
						
		$form->addGroup($row);
		
		if($material_default != null)
			return array($material_element_name=>$material_default);			
	}
	private function create_subnet_row($form, $index, $material_default= null)
	{
		$row = array();		
		$material_element_name = 'subnet['.$index.'][material]';
		$amount_element_name = 'subnet['.$index.'][amount]';
		$row[]=$form->createElement(
			'autoselect', 
			$material_element_name, 
			_M('Material'), 
			array(), array(array('SCTV_MaterialCommon','material_suggestbox'), array(array(), array(), array('SCTV_MaterialCommon', 'material_format'))), array('SCTV_MaterialCommon', 'material_format_display'),
			array(
				'onchange'=>"
					if(this.value == '')
					{
						var amount_element = document.getElementsByName('" . $amount_element_name . "')[0]
						amount_element.value = '';
						amount_element.setAttribute('disabled', 'true');						
					}
					else {
						document.getElementsByName('" . $amount_element_name . "')[0].removeAttribute('disabled');
					}						
				"
			)
		);
	    
		
		$valid_amount_as_number = "
			var amount = jQuery('input[name=\'". $amount_element_name ."\']').val();
			if(isNaN(amount) || +amount < 0)
			{
				jQuery('input[name=\'". $amount_element_name ."\']').text('0');
				jQuery('input[name=\'". $amount_element_name ."\']').val(0);				
			}
		";									
		$amount_element=$form->createElement('text', 'subnet['.$index.'][amount]', __('Amount'),
			array(
				'onchange'=>$valid_amount_as_number				
			)
		);
		
		if($material_default == null)
			$amount_element->setAttribute('disabled', true);
					
		$row[] = $amount_element;
						
		$form->addGroup($row);
		
		if($material_default != null)
			return array($material_element_name=>$material_default);			
	}
	private function create_charge_row($form, $index, $acceptance_date, $material_default= null, $istvbox = false)
	{
		$row = array();
		$material_element_name = 'charge['.$index.'][material]';
		$amount_element_name = 'charge['.$index.'][amount]';
		$price_element_name = 'charge['.$index.'][price]';
		$total_element_name = 'charge['.$index.'][total]';
		$valid_amount_as_number = "
			var amount = jQuery('input[name=\'". $amount_element_name ."\']').val();
			if(isNaN(amount) || +amount < 0)
			{
				jQuery('input[name=\'". $amount_element_name ."\']').text('0');
				jQuery('input[name=\'". $amount_element_name ."\']').val(0);				
			}
			
			var change_amount = 'true';
		";
		 
		$summary_material_js = "									
					var total = jQuery('input[name=\'". $total_element_name ."\']').val();
					
					var summary_material = jQuery('input[name=\'summary_material\']').val();
					var summary_tvbox = jQuery('input[name=\'summary_tvbox\']').val();					
					
					var x;
					if(change_amount == 'true')
						x = jQuery('select[name=\'". $material_element_name . "\']').attr('istvbox');
					else
						x = jQuery('select[name=\'". $material_element_name . "\']').attr('prev_istvbox');
						
					if(x == 'true')
					{
						summary_tvbox = +summary_tvbox - total;
						jQuery('input[name=\'summary_tvbox\']').val(summary_tvbox).change();
					}						
					else
					{
						summary_material = +summary_material - total;
						jQuery('input[name=\'summary_material\']').val(summary_material).change();
					}											
					
					var amount = jQuery('input[name=\'". $amount_element_name ."\']').val();
					var price = jQuery('input[name=\'". $price_element_name ."\']').val();
					var total = Math.round(+amount * +price);
					
					jQuery('input[name=\'". $total_element_name ."\']').val(total);													
								
					x = jQuery('select[name=\'". $material_element_name . "\']').attr('istvbox');
					if(x == 'true')
					{
						summary_tvbox = +summary_tvbox + total;						
						jQuery('input[name=\'summary_tvbox\']').val(summary_tvbox).change();	
					}						
					else
					{
						summary_material = +summary_material + total;	
						jQuery('input[name=\'summary_material\']').val(summary_material).change();
					}																	
		";		
		
		
		$material_element = $form->createElement(
				'autoselect', 
				$material_element_name, 
				_M('Material'), 
				array(), array(array('SCTV_MaterialCommon','material_suggestbox'), array(array(), array(), array('SCTV_MaterialCommon', 'material_format'))), array('SCTV_MaterialCommon', 'material_format_display'), 
				array(
					'istvbox'=>$istvbox?'true':'false',
					'prev_istvbox'=>$istvbox?'true':'false',
					'onchange'=>"
							if(this.value == '')
							{
								var amount_element = document.getElementsByName('" . $amount_element_name . "')[0];
								amount_element.value = '';
								amount_element.setAttribute('disabled', 'true');																	
							}
							else 
							{
								document.getElementsByName('" . $amount_element_name . "')[0].removeAttribute('disabled');
							}
																							
							new Ajax.Request
							(
								'modules/SCTV/Material/get_price.php', 
								{
									method: 'post',
									parameters:{
										material: this.value,
										acceptance_date: '".	$acceptance_date . "',
										cid: Epesi.client_id
									},
									onSuccess:function(t) {
										result = t.responseText.evalJSON();
										jQuery('input[name=\'".$price_element_name."\']').val(result.price);
										prev_istvbox = jQuery('select[name=\'".$material_element_name."\']').attr('istvbox');
										jQuery('select[name=\'".$material_element_name."\']').attr('prev_istvbox', prev_istvbox);										 									
										jQuery('select[name=\'".$material_element_name."\']').attr('istvbox', result.istvbox);
										var change_amount = 'false';
									"
									. $summary_material_js .
									"					
																	
									}
								}
							);
						"
				)
			);
		
		$row[]=$material_element;
							
		$amount_element = $form->createElement('text', $amount_element_name, __('Amount'),
			array(
				'onchange'=>$valid_amount_as_number . $summary_material_js,
				'onkeyup'=>$valid_amount_as_number . $summary_material_js
			)
		);	
			
		if($material_default == null)
			$amount_element->setAttribute('disabled', true);
			
		$row[] = $amount_element;
					
		$row[]=$form->createElement('text', $price_element_name, __('Price'), 
			array(
				'readonly'=>true
			)
		);
		$row[]=$form->createElement('text', 'charge['.$index.'][total]', __('Total'), array('readonly'=>true));
						
		$form->addGroup($row);
		
		if($material_default != null)
		{
			$material_price_istvbox = SCTV_MaterialCommon::get_current_price_istvbox($material_default, $acceptance_date);
			return array($material_element_name=>$material_default, $price_element_name=>$material_price_istvbox['price']);	
		}			
	}
	public function caption(){
		if (isset($this->rb)) return $this->rb->caption();
	}
}
 
?>